define([],

function() {
  var Form = Backbone.View.extend({

    template: _.template($('#form-template').html()),

    events: {
      'click .dlg-save': 'save',
      'click .dlg-close': 'hide',
    },

    formControl: function(type, options) {
      switch (type) {
        case 'bool':
          return '<div class="row"><div class="large-3 columns"><label class="right inline"><%= name %></label></div>' +
                 '<div class="large-9 columns"><div class="switch">' +
                 '  <input type="radio" id="form-<%= name %>-0" value="false" name="<%= name %>" <% if (!value) { %> checked <% } %> /><label for="form-<%= name %>-0" onclick="">Off</label>' +
                 '  <input type="radio" id="form-<%= name %>-1" value="true" name="<%= name %>" <% if (value) { %> checked <% } %> /><label for="form-<%= name %>-1" onclick="">On</label>' +
                 '<span></span></div></div></div>'
        default:
          return '<div class="row"><div class="large-3 columns"><label class="right inline"><%= name %></label></div><div class="large-9 columns"><input type="text" name="<%= name %>" value="<%= value %>" /></div></div>'
      } 
    },

    initialize: function() {
      $('.modal').remove();
      $('body').append(this.render().el);
      this.$('.modal').foundation('reveal', 'open');
 //      this.$('.switch').bootstrapSwitch();
    },

    render: function() {
      var self = this;
      var data = this.model.toFormData();
      var types = this.model.getDataTypes();
      var body = _.map(data, function(v, k) { 
        return _.template(self.formControl(types[k]), { name: k, value: v }); 
      }).join('');
      this.$el.html(this.template({ body: body}));
      return this;
    },

    hide: function() {
      this.$('.modal').foundation('reveal', 'close');
    },

    save: function() {
      // console.log($.io.form($('form')).object());

      var data = $('form').serializeObject();
      if (this.model.isNew()) {
        this.collection.create(data)
      }
      else {
        this.model.save(data);
      }
      this.$('.dlg-close').click();
    },

  });

  return Form;
});

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};